package com.resifind.www.dao.impl;

import com.resifind.www.dao.BrowseDao;
import com.resifind.www.dao.mapper.Mappers;
import com.resifind.www.po.Browse;
import com.resifind.www.util.JdbcUtils;

import java.sql.Connection;
import java.util.List;

/**
 * @author 36069
 */
public class BrowseDaoImpl implements BrowseDao {

    @Override
    public List<Browse> queryBrowseByClientId(int clientId) {
        //language=MySQL
        String sql = """
                select b.*, m.trade_name as trade_name
                from resi_find.browse b
                join resi_find.merchant m on b.merchant_id = m.id
                where b.client_id = ?
                order by b.time desc
                """;
        Object[] params = {clientId};
        return Mappers.browseMapper(sql, params);
    }

    @Override
    public Browse queryBrowseByClientIdAndMerchantId(int clientId, int merchantId) {
        //language=MySQL
        String sql = "select *, null as trade_name from resi_find.browse where client_id = ? and merchant_id = ?";
        Object[] params = {clientId, merchantId};
        List<Browse> browseList = Mappers.browseMapper(sql, params);
        return browseList.isEmpty() ? null : browseList.getFirst();
    }

    @Override
    public boolean addBrowse(int clientId, int merchantId, String time, Connection conn) {
        //language=MySQL
        String sql = "insert into resi_find.browse (client_id, merchant_id, time) values (?, ?, ?)";
        Object[] params = {clientId, merchantId, time};
        return JdbcUtils.update(sql, params, conn);
    }

    @Override
    public boolean updateBrowse(int clientId, int merchantId, String time, Connection conn) {
        //language=MySQL
        String sql = "update resi_find.browse set time = ? where client_id = ? and merchant_id = ?";
        Object[] params = {time, clientId, merchantId};
        return JdbcUtils.update(sql, params, conn);
    }

    @Override
    public boolean deleteBrowse(int clientId, int merchantId, Connection conn) {
        //language=MySQL
        String sql = "delete from resi_find.browse where client_id = ? and merchant_id = ?";
        Object[] params = {clientId, merchantId};
        return JdbcUtils.update(sql, params, conn);
    }

    @Override
    public boolean clearBrowse(int clientId, Connection conn) {
        //language=MySQL
        String sql = "delete from resi_find.browse where client_id = ?";
        Object[] params = {clientId};
        return JdbcUtils.update(sql, params, conn);
    }
}
